<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="username">
      <Input v-model="form.username" placeholder="请输入用户名">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password" v-model="form.password" placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="code" v-if="showKaptcha > 0"  class="vcodeform">
      <Input v-model="form.code" size="large" placeholder="请输入验证码">
      <span slot="prepend">
        <Icon type="lock-combination"></Icon>
      </span>
      <span slot="append">
        <img :src="'/api/code/'+form.codeKey" @click="initVcode" style="height:30px">
      </span>
      </Input>
    </FormItem>
    <div style="text-align:right;"><a @click="goForgetPwd" >忘记密码？</a></div>

    <FormItem>
      <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>

  </Form>
</template>
<script>
export default {
  name: 'LoginForm',
  props: {
    userNameRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  data () {
    return {
      form: {
        username: 'admin',
        password: '',
        codeKey: '',
        code: ''
      }
    }
  },
  computed: {
    showKaptcha: function () {
      // `this` 指向 vm 实例
      return this.$store.state.showKaptcha
    },
    rules () {
      return {
        username: this.userNameRules,
        password: this.passwordRules
      }
    }
  },

  methods: {
    initVcode () {
      let rnd = Math.random().toString() + (new Date()).getTime()
      this.form.codeKey = rnd
    },
    goForgetPwd(){
      this.$router.push({name: "forgetPwd"});
    },
    handleSubmit () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$emit('on-success-valid',
            // userName: this.form.userName,
            // password: this.form.password
            this.form
          )
        }
      })
    }
  },
  created () {
    this.initVcode()
  }
}
</script>
